﻿/*   
    Copyright (C) 2009 Galaktika Corporation ZAO

    This file is a part of Galaktika.BusinessMonitor
 
    Galaktika.BusinessMonitor is a free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
      
    You should have received a copy of the GNU General Public License
    along with Galaktika.BusinessMonitor.  If not, see <http://www.gnu.org/licenses/>.
  
    If GPL v.3 is not suitable for your products or company,
    Galaktika Corp provides Galaktika.BusinessMonitor under a flexible commercial license
    designed to meet your specific usage and distribution requirements.
    If you have already obtained a commercial license from Galaktika Corp,
    you can use this file under those license terms.
*/

using System;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Ranet.AgOlap.Controls.PivotGrid.Controls;
using Galaktika.BI.Runtime.Services;
using System.ComponentModel;
using Ranet.Olap.Core.Data;
using Galaktika.BI.Runtime;
using System.Collections.Generic;
using Galaktika.BI.Silverlight.Controls.General;
using Ranet.AgOlap.Controls.General;
using Ranet.AgOlap.Controls.ContextMenu;
using Galaktika.BI.Extensibility.Dom;
using Ranet.AgOlap.Controls.PivotGrid.Data;
using Galaktika.BI.Charting;
using Ranet.AgOlap.Controls.PivotGrid;
using Ranet.AgOlap.Controls;
using Galaktika.BI.Charting.PivotTable;
using Ranet.AgOlap.Controls.PivotGrid.Conditions;
using System.Windows.Media.Imaging;
using Galaktika.BI.Silverlight.Services;
using Ranet.Olap.Core.Providers;
using Ranet.Olap.Core.Providers.ClientServer;
using Galaktika.BI.Silverlight.Intermediate;
using Galaktika.BI.Extensibility.ComponentModel;
using Galaktika.BI.Extensibility;
using Ranet.Olap.Mdx;
using Ranet.Olap.Core.Providers.MemberActions;

namespace Galaktika.BI.Silverlight.Controls.PivotGrid
{
    public class UpdateablePivotGridControlEx : UpdateablePivotGridControl, IBindableObject, IEditableObject
    {
        public UpdateablePivotGridControlEx() : base()
        {
            ExportToExcelFile = false;

           // base.ExportToExcelClick += new RoutedEventHandler(UpdateablePivotGridControlEx_ExportToExcelClick);
        }

        protected override IDataLoader GetOlapDataLoader()
        {
            IDataLoader loader = new OlapDataLoaderEx(this) { Context = this.Context };
            return loader;
        }

        //void UpdateablePivotGridControlEx_ExportToExcelClick(object sender, RoutedEventArgs e)
        //{
        //    RunExportToExcel();
        //}

        //private void RunExportToExcel()
        //{
        //    IUserTaskManager taskMgr = (IUserTaskManager)this.Context.Services.GetService(typeof(IUserTaskManager));
        //    if (taskMgr != null)
        //    {
        //        IBindingManager manager; 
        //        this.Bindings.TryGetValue("ADataSource", out manager);
        //        String connectionString = manager.DataManager["CONNECION_STRING"].ToString();
        //        String query = manager.DataManager["QUERY"].ToString();
        //        // Парсинг запросов
        //        IExecutionContext exe = (IExecutionContext)Context.Services.GetService(typeof(IExecutionContext));
        //        if (exe != null)
        //        {
        //            query = exe.Parse(Context, query);
        //        }


        //        using (SyncPivotGridService pivotGridService = new SyncPivotGridService())
        //        {

        //            taskMgr.RunTaskAsync("Export To Excel", state =>
        //                    {
        //                        pivotGridService.ExportToExcel(connectionString, query);
        //                        string address = String.Format("{0}PivotGridExportHandler.asmx?token={1}",
        //                                                        Galaktika.BI.Runtime.Services.ServiceManager.GetBaseUri(),
        //                                                        pivotGridService.Token);
        //                taskMgr.Dispatcher.BeginInvoke(() =>
        //                {
        //                    HtmlPage.Window.Invoke("open", address);
        //                });
        //            });
        //        }
        //    }
        //}

        protected override void UpdateCubeCompleted(UpdateCubeArgs e)
        {
            // Просто обновляем контекст. Т.к. данные всеравно придут от сервера через EndEdit
            IExecutionContext context = (IExecutionContext)this.Context.Services.GetService(typeof(IExecutionContext));
            if (context != null)
            {
                this.Context.IsDirty = true;
                context.DoDrillDown(this.Context);
            }
        }

        protected override void MemberActionCompleted(DataLoaderEventArgs e)
        {
            // Просто обновляем контекст. Т.к. данные всеравно придут от сервера через EndEdit
            IExecutionContext context = (IExecutionContext)this.Context.Services.GetService(typeof(IExecutionContext));
            if (context != null)
            {
                this.Context.IsDirty = true;
                context.DoDrillDown(this.Context);
            }
        }

        protected override void ServiceCommandCompleted(ServiceCommandArgs args)
        {
            base.ServiceCommandCompleted(args);

            if (args != null)
            {
                switch (args.Command)
                {
                    case ServiceCommandType.Forward:
                    case ServiceCommandType.Back:
                    case ServiceCommandType.Refresh:
                    case ServiceCommandType.ToBegin:
                    case ServiceCommandType.ToEnd:
                    case ServiceCommandType.HideEmptyColumns:
                    case ServiceCommandType.HideEmptyRows:
                    case ServiceCommandType.ShowEmptyColumns:
                    case ServiceCommandType.ShowEmptyRows:
                    case ServiceCommandType.NormalAxes:
                    case ServiceCommandType.RotateAxes:
                        IExecutionContext context = (IExecutionContext)this.Context.Services.GetService(typeof(IExecutionContext));
                        if (context != null)
                        {
                            this.Context.IsDirty = true;
                            context.DoDrillDown(this.Context);
                        }
                        break;
                }
            }
        }

        public static DependencyProperty ADataSourceProperty = DependencyProperty.Register("ADataSource", typeof(object), typeof(UpdateablePivotGridControl), null);
        public object ADataSource
        {
            get
            {
                return base.GetValue(ADataSourceProperty);
            }
            set
            {
                base.SetValue(ADataSourceProperty, value);
                OlapDataLoaderEx loader = base.OlapDataLoader as OlapDataLoaderEx;
                if (loader != null)
                {
                    IBindingManager manager = null;
                    this.Bindings.TryGetValue("ADataSource", out manager);
                    loader.BindManager = manager;
                }
            }
        }

        String m_MemberVisualizationType = String.Empty;
        /// <summary>
        /// Свойство для отображения в заголовках элементов
        /// </summary>
        public String AMemberVisualizationType
        {
            get { return m_MemberVisualizationType; }
            set { m_MemberVisualizationType = value; }
        }

        public bool AIsUpdateable
        {
            get
            {
                return base.IsUpdateable;
            }
            set
            {
                base.IsUpdateable = value;
            }
        }

        public bool AUseChangesCache
        {
            get
            {
                return base.UseChangesCashe;
            }
            set
            {
                base.UseChangesCashe = value;
            }
        }

        /// <summary>
        /// Определяет возможность использования Expand, Collapse, DrillDown
        /// </summary>
        public bool ARowsIsInteractive
        {
            get
            {
                return base.RowsIsInteractive;
            }
            set
            {
                base.RowsIsInteractive = value;
            }
        }

        /// <summary>
        /// Определяет возможность использования Expand, Collapse, DrillDown
        /// </summary>
        public bool AColumnsIsInteractive
        {
            get
            {
                return base.ColumnsIsInteractive;
            }
            set
            {
                base.ColumnsIsInteractive = value;
            }
        }

        public string AConcretizeMdxObjectFunction { get; set; }

        #region Действия для областей

        CustomList<ActionInfo> m_ACellsAreaContextActions = null;
        /// <summary>
        /// Действия для области ячеек
        /// </summary>
        public CustomList<ActionInfo> ACellsAreaContextActions
        {
            get
            {
                return m_ACellsAreaContextActions;
            }
            set
            {
                m_ACellsAreaContextActions = value;
            }
        }

        CustomList<ActionInfo> m_ARowsAreaContextActions = null;
        /// <summary>
        /// Действия для области строк
        /// </summary>
        public CustomList<ActionInfo> ARowsAreaContextActions
        {
            get
            {
                return m_ARowsAreaContextActions;
            }
            set
            {
                m_ARowsAreaContextActions = value;
            }
        }

        CustomList<ActionInfo> m_AColumnsAreaContextActions = null;
        /// <summary>
        /// Действия для области столбцов
        /// </summary>
        public CustomList<ActionInfo> AColumnsAreaContextActions
        {
            get
            {
                return m_AColumnsAreaContextActions;
            }
            set
            {
                m_AColumnsAreaContextActions = value;
            }
        }
        #endregion Действия для областей

        #region Действия для Expand, Collapse, DrillDown
        BrickActionInvoker m_ADrillDownAction = null;
        [Browsable(false)]
        public BrickActionInvoker ADrillDownAction
        {
            get
            {
                return m_ADrillDownAction;
            }
            set
            {
                m_ADrillDownAction = value;
            }
        }

        BrickActionInvoker m_AExpandAction = null;
        [Browsable(false)]
        public BrickActionInvoker AExpandAction
        {
            get
            {
                return m_AExpandAction;
            }
            set
            {
                m_AExpandAction = value;
            }
        }

        BrickActionInvoker m_ACollapseAction = null;
        [Browsable(false)]
        public BrickActionInvoker ACollapseAction
        {
            get
            {
                return m_ACollapseAction;
            }
            set
            {
                m_ACollapseAction = value;
            }
        }

        protected override void PerformMemberAction(MemberActionEventArgs e)
        {
            //if(Context != null)
            //    Context.IsDirty = true;

            // Выполняем дополнительно экшен ПЕРЕД выполнением ДРИЛЛ-опреации
            BrickActionInvoker invoker = null;

            switch (e.Action)
            {
                case MemberActionType.DrillDown:
                    invoker = ADrillDownAction;
                    break;
                case MemberActionType.Expand:
                    invoker = AExpandAction;
                    break;
                case MemberActionType.Collapse:
                    invoker = ACollapseAction;
                    break;
            }

            if (invoker != null && e.Member != null)
            {
                List<ArgumentEntry> args = new List<ArgumentEntry>(invoker.Parameters);
                args.Add(new ArgumentEntry("HIERARCHY_UNIQUE_NAME", e.Member.HierarchyUniqueName));
                args.Add(new ArgumentEntry("MEMBER_UNIQUE_NAME", e.Member.UniqueName));
                ScriptEngine.Execute(this, invoker.Action, args);
            }

            // Выполнем базовую реализацию 
            base.PerformMemberAction(e);
        }
        #endregion Действия для Expand, Collapse, DrillDown

        public bool AUseToolBar
        {
            get
            {
                return base.ShowToolBar;
            }
            set
            {
                base.ShowToolBar = value;
            }
        }

        #region Настройки для подсказок
        public bool AUseRowsAreaHint
        {
            get
            {
                return base.UseRowsAreaHint;
            }
            set
            {
                base.UseRowsAreaHint = value;
            }
        }

        public bool AUseColumnsAreaHint
        {
            get
            {
                return base.UseColumnsAreaHint;
            }
            set
            {
                base.UseColumnsAreaHint = value;
            }
        }

        public bool AUseCellsAreaHint
        {
            get
            {
                return base.UseCellsAreaHint;
            }
            set
            {
                base.UseCellsAreaHint = value;
            }
        }
        #endregion Настройки для подсказок

        protected override void CellsControl_ContextMenuCreated(object sender, EventArgs e)
        {
            base.CellsControl_ContextMenuCreated(sender, e);

            CustomContextMenu contextMenu = base.PivotGrid.Cells_ContextMenu;
            if (contextMenu != null)
            {
                if (ACellsAreaContextActions != null && ACellsAreaContextActions.Count > 0)
                {
                    if (contextMenu.Items.Count > 0)
                    {
                        contextMenu.AddMenuSplitter();
                    }

                    foreach (ActionInfo info in ACellsAreaContextActions)
                    {
                        ContextMenuItem item = new ContextMenuItem(info.ACaption);
                        item.ItemClick += new EventHandler(CellsAreaContextMenu_ItemClick);
                        item.Tag = info;
                        item.Icon = UriResources.Images.ActionNode16;
                        contextMenu.AddMenuItem(item);
                    }
                }

            }
        }

        void CellsAreaContextMenu_ItemClick(object sender, EventArgs e)
        {
            ContextMenuItem item = sender as ContextMenuItem;
            if (item != null && item.Tag != null && PivotGrid.Cells_ContextMenu != null)
            {
                if (item.Tag is ActionInfo)
                {
                    ActionInfo ai = item.Tag as ActionInfo;
                    if (ai != null && ai.AActionInvoker != null && ((BrickActionInvoker)ai.AActionInvoker).Action != null)
                    {
                        List<ArgumentEntry> args = new List<ArgumentEntry>(((BrickActionInvoker)ai.AActionInvoker).Parameters);

                        // Формируем параметры для вызываемого экшена.
                        // Выбранных ячеек может быть несколько и для каждой из них нужно передать тапл
                        // Поэтому ключом будет число от 0 до ......
                        // значением будет сериализованный список строк

                        //RaiseLogMessage("Execute Context Action: " + ((BrickActionInvoker)ai.AActionInvoker).Action.Name);

                        String cubeName = String.Empty;
                        String connectionString = String.Empty;
                        if (CellSetProvider != null && CellSetProvider.CellSet_Description != null)
                        {
                            cubeName = CellSetProvider.CellSet_Description.CubeName;
                            connectionString = CellSetProvider.CellSet_Description.Connection.ConnectionString;
                        }

                        int key = 0;

                        args.Add(new ArgumentEntry("CUBE_NAME", cubeName));
                        args.Add(new ArgumentEntry("CONNECTION_STRING", connectionString));

                        CellControl cell_control = PivotGrid.Cells_ContextMenu.Tag as CellControl;
                        if(cell_control != null && cell_control.Cell != null)
                        {
                            List<MemberDescription> str_tuple = new List<MemberDescription>();
                            IDictionary<String, MemberInfo> tuple = cell_control.Cell.GetTuple();
                            foreach (KeyValuePair<String, MemberInfo> kp in tuple)
                            {
                                if (kp.Value != null)
                                {
                                    String uniqName = kp.Value.UniqueName;
                                    str_tuple.Add(new MemberDescription(kp.Key, uniqName));
                                }
                            }

                            args.Add(new ArgumentEntry(key.ToString(), XmlUtility.Obj2XmlStr(str_tuple, "")));
                            String cellValue_Str = String.Empty;
                            if (cell_control.Cell.Value != null)
                            {
                                // В качестве разделителя для числа обязательно должна использоватьеся точка (т.к. эта строка будет помещена в МDX)
                                cellValue_Str = cell_control.Cell.Value.ToString();
                                cellValue_Str = cellValue_Str.Replace(System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator, ".");
                            }
                            args.Add(new ArgumentEntry(key.ToString() + "_Value", cellValue_Str));
                            
                        }

                        ScriptEngine.Execute(new MockCaller(this.Context), ((BrickActionInvoker)ai.AActionInvoker).Action, args);
                    }
                    return;
                }
            }
        }

        protected override void ColumnsControl_ContextMenuCreated(object sender, EventArgs e)
        {
            base.ColumnsControl_ContextMenuCreated(sender, e);

            CustomContextMenu contextMenu = PivotGrid.Columns_ContextMenu;
            if (contextMenu != null)
            {
                if (AColumnsAreaContextActions != null && AColumnsAreaContextActions.Count > 0)
                {
                    if (contextMenu.Items.Count > 0)
                    {
                        contextMenu.AddMenuSplitter();
                    }

                    foreach (ActionInfo info in AColumnsAreaContextActions)
                    {
                        ContextMenuItem item = new ContextMenuItem(info.ACaption);
                        item.ItemClick += new EventHandler(ColumnsAreaContextMenu_ItemClick);
                        item.Tag = info;
                        item.Icon = UriResources.Images.ActionNode16;
                        contextMenu.AddMenuItem(item);
                    }
                }
            }
        }

        protected override void RowsControl_ContextMenuCreated(object sender, EventArgs e)
        {
            base.RowsControl_ContextMenuCreated(sender, e);

            CustomContextMenu contextMenu = PivotGrid.Rows_ContextMenu;
            if (contextMenu != null)
            {
                if (ARowsAreaContextActions != null && ARowsAreaContextActions.Count > 0)
                {
                    if (contextMenu.Items.Count > 0)
                    {
                        contextMenu.AddMenuSplitter();
                    }

                    foreach (ActionInfo info in ARowsAreaContextActions)
                    {
                        ContextMenuItem item = new ContextMenuItem(info.ACaption);
                        item.ItemClick += new EventHandler(RowsAreaContextMenu_ItemClick);
                        item.Tag = info;
                        item.Icon = UriResources.Images.ActionNode16;
                        contextMenu.AddMenuItem(item);
                    }
                }
            }
        }

        void RowsAreaContextMenu_ItemClick(object sender, EventArgs e)
        {
            ContextMenuItem item = sender as ContextMenuItem;
            if (item != null && item.Tag != null && PivotGrid.Rows_ContextMenu != null)
            {
                if (item.Tag is ActionInfo)
                {
                    ActionInfo ai = item.Tag as ActionInfo;
                    if (ai != null && ai.AActionInvoker != null && ((BrickActionInvoker)ai.AActionInvoker).Action != null)
                    {
                        List<ArgumentEntry> args = new List<ArgumentEntry>(((BrickActionInvoker)ai.AActionInvoker).Parameters);

                        MemberInfo mi = PivotGrid.Rows_ContextMenu.Tag as MemberInfo;
                        if (mi != null)
                        {
                            args.Add(new ArgumentEntry(mi.HierarchyUniqueName, mi.UniqueName));
                        }

                        ScriptEngine.Execute(new MockCaller(this.Context), ((BrickActionInvoker)ai.AActionInvoker).Action, args);
                    }
                    return;
                }
            }
        }

        void ColumnsAreaContextMenu_ItemClick(object sender, EventArgs e)
        {
            ContextMenuItem item = sender as ContextMenuItem;
            if (item != null && item.Tag != null && PivotGrid.Columns_ContextMenu != null)
            {
                if (item.Tag is ActionInfo)
                {
                    ActionInfo ai = item.Tag as ActionInfo;
                    if (ai != null && ai.AActionInvoker != null && ((BrickActionInvoker)ai.AActionInvoker).Action != null)
                    {
                        List<ArgumentEntry> args = new List<ArgumentEntry>(((BrickActionInvoker)ai.AActionInvoker).Parameters);

                        MemberInfo mi = PivotGrid.Columns_ContextMenu.Tag as MemberInfo;
                        if (mi != null)
                        {
                            args.Add(new ArgumentEntry(mi.HierarchyUniqueName, mi.UniqueName));
                        }

                        ScriptEngine.Execute(new MockCaller(this.Context), ((BrickActionInvoker)ai.AActionInvoker).Action, args);
                    }
                    return;
                }
            }
        }

        #region IBindableObject Members

        IBindingContext m_Context = null;
        public IBindingContext Context {
            get {
                return m_Context;
            }
            set {
                m_Context = value;
                if (m_Context != null)
                {
                    base.LogManager = new LogManagerEx(m_Context);
                }

                OlapDataLoaderEx loader = OlapDataLoader as OlapDataLoaderEx;
                if (loader != null)
                {
                    loader.Context = value;
                }

                if (m_Context != null)
                {
                    base.IsolatedStoragePrefix = (string)m_Context.UserData["_$Id"];
                }
                else
                {
                    base.IsolatedStoragePrefix = String.Empty;
                }
            } 
        }

        private IDictionary<string, IBindingManager> m_Bindings;
        public IDictionary<string, IBindingManager> Bindings
        {
            get
            {
                if (m_Bindings == null)
                {
                    m_Bindings = new SafeDictionary<string, IBindingManager>();
                }

                return m_Bindings;
            }
        }

        #endregion

        #region IEditableObject Members

        bool m_Initialized = false;

        public void BeginEdit()
        {
            // Сохраняем размеры -  это поможет восстановить данные размеры в EndEdit 
            // Это нужно когда на форме происходят изменения по инициативе других элементов
            if (m_Initialized)
            {
                ExportSizeInfo();
            }
        }

        public void CancelEdit()
        {
        }

        private MdxObject ConcretizeMdxObject(MdxObject obj, MdxActionContext context)
        {
            if (m_FunctionConcretize == null)
            {
                return null;
            }

            return m_FunctionConcretize.Invoke(null, new object[] { obj, context }) as MdxObject;
        }

        private System.Reflection.MethodInfo m_FunctionConcretize;

        public void EndEdit()
        {
            IBindingManager manager = null;
            this.Bindings.TryGetValue("ADataSource", out manager);
            if (manager != null && manager.DataManager != null && manager.DataManager["UPDATE_SCRIPT"] != null)
            {
                UpdateScript = manager.DataManager["UPDATE_SCRIPT"].ToString();
            }
            else
            {
                UpdateScript = String.Empty;
            }

            if (!string.IsNullOrEmpty(this.AConcretizeMdxObjectFunction))
            {
                var dataManager = manager.DataManager as PivotDataManagerBase;
                if (dataManager != null)
                {
                    var app = this.Context.Services.GetService<IAppManager>();
                    if (app != null)
                    {
                        m_FunctionConcretize = ScriptEngine.ResolveFunction(
                            app.ClientAssembly,
                            this.AConcretizeMdxObjectFunction);
                        ScriptEngine.SetCurrentCaller(this.Context, app.ClientAssembly);
                    }

                    dataManager.ConcretizeMdxObject = this.ConcretizeMdxObject;
                }
            }

            try{
                object obj = Enum.Parse(typeof(MemberVisualizationTypes), AMemberVisualizationType, true);
                if (obj != null && obj is MemberVisualizationTypes)
                    base.MemberVisualizationType = (MemberVisualizationTypes)obj;
            }
            catch{
                base.MemberVisualizationType = MemberVisualizationTypes.Caption;
            }

            //if (this.Context.UserData.ContainsKey("RESET_USER_MDX_ACTIONS"))
            //{
            //    var pivotManager = manager.DataManager as PivotDataManagerBase;
            //    if (pivotManager != null)
            //    {
            //        pivotManager.History.ClearHistory();
            //    }
            //}

            OlapDataLoaderEx loader = OlapDataLoader as OlapDataLoaderEx;
            if (loader != null)
            {
                loader.BindManager = manager;
            }

            ApplyStyleConditions();

            CellSetData description = this.ADataSource as CellSetData;
            Initialize(description);
            //ImportSizeInfo();
            //UpdateButtons();
            m_Initialized = true;
        }

        #endregion

        void ApplyStyleConditions()
        {
            base.CustomCellsConditions = null;
            if (AStyleConditions != null)
            {
                foreach (StyleConditionsDescriptor cond in AStyleConditions)
                {
                    CellConditionsDescriptor cell_conditions_descr = new CellConditionsDescriptor(cond.ConditionsOwner);
                    foreach(StyleCondition style in cond.Conditions)
                    {
                        CellConditionType type = CellConditionType.None;
                        switch(style.Condition)
                        {
                            case FormatConditionEnum.Between:
                                type = CellConditionType.Between;
                                break;
                            case FormatConditionEnum.Equal:
                                type = CellConditionType.Equal;
                                break;
                            case FormatConditionEnum.Greater:
                                type = CellConditionType.Greater;
                                break;
                            case FormatConditionEnum.GreaterOrEqual:
                                type = CellConditionType.GreaterOrEqual;
                                break;
                            case FormatConditionEnum.Less:
                                type = CellConditionType.Less;
                                break;
                            case FormatConditionEnum.LessOrEqual:
                                type = CellConditionType.LessOrEqual;
                                break;
                            case FormatConditionEnum.None:
                                type = CellConditionType.None;
                                break;
                            case FormatConditionEnum.NotBetween:
                                type = CellConditionType.NotBetween;
                                break;
                            case FormatConditionEnum.NotEqual:
                                type = CellConditionType.NotEqual;
                                break;
                        }

                        CellAppearanceObject cell_appearance = new CellAppearanceObject(style.Appearance.BackColor, 
                            style.Appearance.BorderColor, 
                            style.Appearance.ForeColor);
                        if (!String.IsNullOrEmpty(style.Appearance.AssemblyName) &&
                            !String.IsNullOrEmpty(style.Appearance.AResName))
                        {
                            BitmapImage image = UriResources.GetImage(UriResources.GetResourceString(style.Appearance.AssemblyName, style.Appearance.AResName.Remove(0, style.Appearance.AssemblyName.Length + 1)));
                            cell_appearance.CustomImage = image;
                        }

                        cell_appearance.ProgressBarOptions = new CellProgressBarOptions();
                        cell_appearance.ProgressBarOptions.StartColor = style.Appearance.ProgressBarOptions.StartColor;
                        cell_appearance.ProgressBarOptions.EndColor = style.Appearance.ProgressBarOptions.EndColor;
                        cell_appearance.ProgressBarOptions.MinValue = style.Appearance.ProgressBarOptions.MinValue;
                        cell_appearance.ProgressBarOptions.MaxValue = style.Appearance.ProgressBarOptions.MaxValue;
                        cell_appearance.ProgressBarOptions.IsIndeterminate = style.Appearance.ProgressBarOptions.IsBroken;

                        cell_appearance.Options = new CellAppearanceOptions();
                        cell_appearance.Options.IgnoreAllOptions = style.Appearance.Options.IgnoreAllOptions;
                        cell_appearance.Options.UseAllOptions = style.Appearance.Options.UseAllOptions;
                        cell_appearance.Options.UseBackColor = style.Appearance.Options.UseBackColor;
                        cell_appearance.Options.UseBorderColor = style.Appearance.Options.UseBorderColor;
                        cell_appearance.Options.UseForeColor = style.Appearance.Options.UseForeColor;
                        cell_appearance.Options.UseImage = style.Appearance.Options.UseImage;
                        cell_appearance.Options.ShowValue = style.Appearance.Options.ShowValue;
                        cell_appearance.Options.UseProgressBar = style.Appearance.Options.UseProgressBar;

                        CellCondition cell_cond = new CellCondition(type, style.Value1, style.Value2, cell_appearance);
                        cell_conditions_descr.Conditions.Add(cell_cond);
                    }
                    if (base.CustomCellsConditions == null)
                        base.CustomCellsConditions = new List<CellConditionsDescriptor>();
                    base.CustomCellsConditions.Add(cell_conditions_descr);
                }
            }
        }

        protected override void Initialize(CellSetData cs_descr)
        {
            //IUserTaskManager taskManager = (IUserTaskManager)Context.Services.GetService(typeof(IUserTaskManager));
            //if (taskManager != null)
            //{
            //    taskManager.RunTask(Localization.AppTask_InitializingPivotGrid, delegate { CallBase_Initialize(cs_descr); });
            //    return;
            //}
            CallBase_Initialize(cs_descr);
        }

        void CallBase_Initialize(CellSetData cs_descr)
        {
            base.Initialize(cs_descr);
            if (cs_descr != null)
            {
                Connection = cs_descr.Connection.ConnectionID;
            }
            else
            {
                Connection = String.Empty;
            }
        }

        StyleConditionsList<StyleConditionsDescriptor> m_StyleConditions = null;
        public StyleConditionsList<StyleConditionsDescriptor> AStyleConditions
        {
            get { return m_StyleConditions; }
            set { m_StyleConditions = value; }
        }

        public bool AUseModifyDataConfirm
        {
            get
            {
                return base.UseModifyDataConfirm;
            }
            set
            {
                base.UseModifyDataConfirm = value;
            }
        }

        #region Внешний вид - SILVERLIGHT

        public double AFontSize
        {
            get { return base.DefaultFontSize; }
            set { base.DefaultFontSize = value; }
        }

        public double ADefaultMemberWidth
        {
            get { return base.DefaultMemberWidth; }
            set { base.DefaultMemberWidth = value; }
        }

        public double ADefaultMemberHeight
        {
            get { return base.DefaultMemberHeight; }
            set { base.DefaultMemberHeight = value; }
        }

        public double AMinMemberHeight
        {
            get { return base.MinMemberHeight; }
            set { base.MinMemberHeight = value; }
        }

        public double AMinMemberWidth
        {
            get { return base.MinMemberWidth; }
            set { base.MinMemberWidth = value; }
        }

        public double ARowsDrillDownMemberOffset
        {
            get { return base.RowsDrillDownMemberOffset; }
            set { base.RowsDrillDownMemberOffset = value; }
        }
        #endregion Внешний вид - SILVERLIGHT
    }
}
